<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="组织名称" prop="orgName">
        <el-input v-model="queryParams.orgName" placeholder="请输入组织名称" size="small" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="组织状态" clearable size="small">
          <el-option v-for="option in options.sysOrgStatusOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:org:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" row-key="id" :data="orgList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="orgName" label="组织名称" width="260" />
      <el-table-column prop="orgName" label="组织类型" :formatter="orgTypeFormat" />
      <el-table-column prop="treeSort" label="排序" />
      <el-table-column prop="status" label="状态" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['system:org:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['system:org:insert']" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button v-if="scope.row.pid != 0" v-hasPermission="['system:org:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改组织对话框 -->
    <el-dialog :title="sysOrgFormDialog.title" :visible.sync="sysOrgFormDialog.visible" :close-on-click-modal="false" width="600px" append-to-body>
      <el-form ref="sysOrgForm" :model="sysOrgFormData" :rules="sysOrgFormRules" label-width="80px">
        <el-row :span="24">
          <el-col v-if="sysOrgFormData.pid">
            <el-form-item label="上级组织" prop="pid">
              <treeselect v-model="sysOrgFormData.pid" :options="options.sysOrgOptions" :normalizer="normalizer" placeholder="选择上级组织" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织名称" prop="orgName">
              <el-input v-model="sysOrgFormData.orgName" placeholder="请输入组织名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgType">
              <el-select v-model="sysOrgFormData.orgType" placeholder="请选择组织类型" clearable size="small">
                <el-option v-for="option in options.sysOrgTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="sysOrgFormData.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="sysOrgFormData.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="sysOrgFormData.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="treeSort">
              <el-input-number v-model="sysOrgFormData.treeSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织状态">
              <el-radio-group v-model="sysOrgFormData.status">
                <el-radio v-for="option in options.sysOrgStatusOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSysOrgFormDialog">确 定</el-button>
        <el-button @click="resetSysOrgFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OrgApi from '@/api/system/OrgApi'
import DictValueApi from '@/api/system/DictValueApi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const defaultSysOrgFormData = {
  id: null,
  pid: '0',
  orgName: null,
  treeSort: null,
  leader: null,
  phone: null,
  email: null,
  status: '0'
}
export default {
  name: 'SysOrg',
  components: { Treeselect },
  data() {
    return {
      options: {
        sysOrgOptions: [],
        sysOrgTypeOptions: [],
        sysOrgStatusOptions: []
      },
      queryParams: {
        orgName: undefined,
        status: undefined
      },
      orgList: [],
      sysOrgFormDialog: {
        title: '',
        visible: false
      },
      sysOrgFormData: Object.assign({}, defaultSysOrgFormData),
      sysOrgFormRules: {
        pid: [{ required: true, message: '上级组织不能为空', trigger: 'blur' }],
        orgName: [{ required: true, message: '组织名称不能为空', trigger: 'blur' }],
        orgType: [{ required: true, message: '组织类型不能为空', trigger: 'change' }],
        treeSort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
      },
      loading: true,
      searchVisible: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_org_type' }).then(response => {
        this.options.sysOrgTypeOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_enable_disable' }).then(response => {
        this.options.sysOrgStatusOptions = response.data
      })
    },
    handleAdd(row) {
      this.openSysOrgFormDialog('add', row.id)
    },
    handleRemove(row) {
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return OrgApi.remove(row.id)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      this.openSysOrgFormDialog('edit', row.id)
    },
    handleQuery() {
      this.loading = true
      OrgApi.list(this.queryParams).then(response => {
        this.orgList = this.$common.list2Tree(response.data)
        this.loading = false
      }, () => {
        this.loading = false
      })
      OrgApi.treeSelect().then(response => {
        const root = { id: 0, label: '主类目', children: [] }
        root.children = response.data
        this.options.sysOrgOptions.push(root)
      })
    },
    openSysOrgFormDialog(type, id) {
      this.resetSysOrgFormDialog()
      this.sysOrgFormDialog.visible = true
      if (type === 'add') {
        this.sysOrgFormDialog.title = '组织-添加'
        if (id) {
          this.sysOrgFormData.pid = id
        }
      }
      if (type === 'edit') {
        this.sysOrgFormDialog.title = '组织-修改'
        OrgApi.get(id).then(response => {
          this.sysOrgFormData = response.data
        })
      }
    },
    confirmSysOrgFormDialog() {
      this.$refs['sysOrgForm'].validate(valid => {
        if (valid) {
          if (this.sysOrgFormData.id) {
            OrgApi.edit(this.sysOrgFormData).then(response => {
              this.$message.success('修改成功')
              this.sysOrgFormDialog.visible = false
              this.handleQuery()
            })
          } else {
            OrgApi.add(this.sysOrgFormData).then(response => {
              this.$message.success('新增成功')
              this.sysOrgFormDialog.visible = false
              this.handleQuery()
            })
          }
        }
      })
    },
    resetSysOrgFormDialog() {
      this.sysOrgFormDialog = {
        title: '',
        visible: false
      }
      this.sysOrgFormData = Object.assign({}, defaultSysOrgFormData)
      this.resetForm('sysOrgForm')
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return node
    },
    orgTypeFormat(row) {
      return this.$common.getDictValueName(this.options.sysOrgTypeOptions, row.orgType)
    },
    statusFormat(row) {
      return this.$common.getDictValueName(this.options.sysOrgStatusOptions, row.status)
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
